#include "cilent.h"
#define __BIG_FILE_SIZE__ (100*1024*1024) // 大文件边界

// 服务端
int putsCommand(int sockfd,char *filename){                                  
    // 发送文件名
    struct stat st;

    /* int flag = 1; */

    /* if(stat(full_path ,&st) == -1 || S_ISDIR(st.st_mode)){ */
    /*     flag = 0; */
    /* } */

    /* sendn(sockfd,&flag,sizeof(flag)); */

    /* if(flag == 0){ */
    /*     printf("文件不存在或者是目录文件！\n"); */
    /*     return -1; */
    /* } */
    int ret = 0;
    memset(&st,0,sizeof(st));
    stat(filename,&st);
    int namelen = strlen(filename);
    sendn(sockfd,&namelen,sizeof(namelen));
    sendn(sockfd,filename,namelen);
    printf("filename = %s\n",filename);

    // 发送文件大小
    unsigned long filesize = st.st_size;
    sendn(sockfd,&filesize,sizeof(filesize));
    // 打开文件
    int filefd = open(filename,O_RDONLY);
    printf("filefd = %d\n",filefd);
    if(filefd == -1){
        printf("filefd failed!\n");
        return -1;
    }
    
    // 接收客户端的当前大小
    unsigned long offset = 0;
    ret = recvn(sockfd,&offset,sizeof(offset));
    printf("ret = %d\n",ret);

    lseek(filefd,offset,SEEK_SET);
    
    unsigned long sent = offset;
    if(filesize  > __BIG_FILE_SIZE__){
        char buf[4096];
        int ret = 0;
        while(sent < filesize){
            int sendsize = (filesize - sent > sizeof(buf)) ? sizeof(buf):(filesize - sent);
            ret = read(filefd,buf,sendsize);
            if(ret <= 0) break;
            
            sendn(sockfd,buf,ret);
            sent += ret;
            printf("发送进度：%5.2f%%\r",100.00*sent / filesize);
            fflush(stdout);
        }
    }else{
        char buf [1024];
        int ret = 0;

        while(sent < filesize){
            int sendsize = (filesize - sent > sizeof(buf))? sizeof(buf):(filesize - sent);
            ret = read(filefd,buf,sendsize);
            if(ret <= 0) break;

            int len = ret;
            sendn(sockfd,&len,sizeof(len));
            sendn(sockfd,buf,len);

            sent += len;
                printf("发送进度：%5.2f%%\r",100.00 * sent / filesize);
                fflush(stdout);
        }
    }

    printf("文件发送完成！总字节数：%lu\n",sent);
    close(filefd);
    return 0;
}

